package com.lin.java.tool.send.factory;

import com.lin.java.tool.send.enums.SendEnum;
import com.lin.java.tool.send.ex.CustomSendException;
import com.lin.java.tool.send.email.EmailStrategy;
import lombok.Setter;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: linjiang
 * @date: 2025/1/17
 */
@Setter
public class EmailFactory {

    private String host;

    private Integer port;

    private String username;

    private String password;

    private String protocol;

    private String defaultEncoding;

    private final Map<Class<? extends EmailStrategy>, EmailStrategy> strategyMap = new HashMap<>();

    public EmailFactory(String host, Integer port, String username, String password, String protocol, String defaultEncoding) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.protocol = protocol;
        this.defaultEncoding = defaultEncoding;
    }

    public void addStrategy(EmailStrategy strategy) {
        strategyMap.put(strategy.getClass(), strategy);
    }

    /**
     * 创建短信策略
     *
     * @return
     */
    public EmailStrategy getEmailStrategy(Class<? extends EmailStrategy> clazz) {
        EmailStrategy strategy = strategyMap.get(clazz);
        if (Objects.isNull(strategy)) {
            throw new CustomSendException(SendEnum.SEND_FAIl.getCode(), "邮箱服务不存在！");
        }
        return strategy;
    }

    /**
     * 获取email发射器
     *
     * @return
     */
    public JavaMailSender getEmailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setUsername(username);
        sender.setPassword(password);
        sender.setHost(host);
        sender.setPort(port);
        sender.setProtocol(protocol);
        sender.setDefaultEncoding(defaultEncoding);
        return sender;
    }

}
